package cn.wikiflyer.beikang.act.home;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;

import net.tsz.afinal.annotation.view.ViewInject;
import android.content.ClipDescription;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.wikiflyer.beikang.BaseActivity;
import cn.wikiflyer.beikang.R;
import cn.wikiflyer.beikang.act.home.bean.NewsDetailBean;
import cn.wikiflyer.beikang.bean.base.BKBaseBean;
import cn.wikiflyer.beikang.utils.BKUtils;
import cn.wk.libs4a.net.WKAsyncTaskPro;
import cn.wk.libs4a.utils.L;
import cn.wk.libs4a.utils.WKTimeUtils;
import cn.wk.libs4a.view.WKHeader;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.utils.Log;

/**
 * 活动页面
 */
public class NewsAct extends BaseActivity {

	@ViewInject(id = R.id.header)
	private WKHeader header;
	
	private LinearLayout ll_parent;
	
	private TextView tv_title;
	private TextView tv_date;
	private TextView tv_content;

	private IntentBean bean = null;
	private String title = null;

	@Override
	public void getIntentData(Bundle savedInstanceState) {
		super.getIntentData(savedInstanceState);
		try {
			bean = (IntentBean) getIntent().getSerializableExtra("bean");
			title = getIntent().getExtras().getString("title");
			if (title != null) {
				getHeader().setTitle(title);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void loadXml() {
		setContentView(R.layout.bk_act_home_news_web);
		initSize();
	}

	@Override
	public void init() {
		header.setClickListener(null, null, new OnClickListener() {
			public void onClick(View arg0) {
				app().shareFenxiang(NewsAct.this);
			}
		});
		ll_parent = (LinearLayout) findViewById(R.id.ll_parent);
		tv_title = (TextView) findViewById(R.id.textView_title);
		tv_date = (TextView) findViewById(R.id.textView_date);
		tv_content = (TextView) findViewById(R.id.textView_content);
	}

	@Override
	public void setData() {
		if (bean != null) {
			new GetNewsDetailTask(ctx);
		}
	}
	
	/**
	 * 获取咨询详情数据
	 */
	class GetNewsDetailTask extends WKAsyncTaskPro {
		public GetNewsDetailTask(Context context) {
			super(context);
		}

		@Override
		protected String doInBackground(boolean... isLocal) {
			return app().net.getNewsDetail("" + bean.catid, "" + bean.id,
					isLocal);
		}

		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			Type cvbType = new TypeToken<BKBaseBean<NewsDetailBean>>() {
			}.getType();
			Gson gson = new Gson();
			BKBaseBean<NewsDetailBean> base = gson.fromJson(result, cvbType);
			if (base.status == 1) {
				updateUI(base.data);
			} else {
				Toast.makeText(ctx, "获取数据失败", Toast.LENGTH_SHORT).show();
			}
		}
	}
	public static  String ToDBC(String input) {
		   char[] c = input.toCharArray();
		   for (int i = 0; i< c.length; i++) {
		       if (c[i] == 12288) {
		         c[i] = (char) 32;
		         continue;
		       }if (c[i]> 65280&& c[i]< 65375)
		          c[i] = (char) (c[i] - 65248);
		       }
		   return new String(c);
		}
	/**
	 * 更新数据
	 */
	public void updateUI(final NewsDetailBean mNewsDetailBean) {
		tv_title.setText("" + mNewsDetailBean.title);
		tv_date.setText("" + WKTimeUtils.formatTime(mNewsDetailBean.inputtime));
		// Html.f
		tv_content.setMovementMethod(ScrollingMovementMethod.getInstance()); // 设置滚动
		final MyHandler myHandler = new MyHandler(this);
		Thread t = new Thread(new Runnable() {
			Message msg = Message.obtain();
			@Override
			public void run() {
				/**
				 * 要实现图片的显示需要使用Html.fromHtml的一个重构方法：public static Spanned
				 * fromHtml (String source, Html.ImageGetterimageGetter,
				 * Html.TagHandler
				 * tagHandler)其中Html.ImageGetter是一个接口，我们要实现此接口，在它的getDrawable
				 * (String source)方法中返回图片的Drawable对象才可以。
				 */
				ImageGetter imageGetter = new ImageGetter() {
					@Override
					public Drawable getDrawable(String source) {
						URL url;
						Drawable drawable = null;
						try {
							url = new URL(source);
							drawable = Drawable.createFromStream(
									url.openStream(), null);
							// drawable.setBounds(0,
							// 0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
							// int paddingValue = BKUtils.px2dip(ctx, 10);
							int paddingValue = BKUtils.dip2px(ctx, 10);
							Log.e("wj", "padding :" + paddingValue);
//							drawable.setBounds(paddingValue,0,width - 2 * paddingValue,
//									drawable.getIntrinsicHeight()* (width / drawable.getIntrinsicWidth()));
							drawable.setBounds(0,0,width,drawable.getIntrinsicHeight()* (width / drawable.getIntrinsicWidth()));
						} catch (MalformedURLException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						return drawable;
					}
				};
				CharSequence test = Html.fromHtml(ToDBC(mNewsDetailBean.content),imageGetter, null);
				msg.what = 0x101;
				msg.obj = test;
				myHandler.sendMessage(msg);
			}
		});
		t.start();
	}

	/*
	 * Handler
	 * 类应该应该为static类型，否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类，那
	 * 么它也会保持它所在的外部类的引用。为了避免泄露这个外部类，应该将Handler声明为static嵌套类，并且使用对外部类的弱应用。
	 */
	private static class MyHandler extends Handler {
		WeakReference<NewsAct> mActivity;

		public MyHandler(NewsAct activity) {
			mActivity = new WeakReference<NewsAct>(activity);
		}
		@Override
		public void handleMessage(Message msg) {
			NewsAct theActivity = mActivity.get();
			if (msg.what == 0x101) {
				L.wj("content :"+(CharSequence)msg.obj);
				theActivity.tv_content.setText(msg.obj.toString());
			}
			super.handleMessage(msg);
		}
	}

}
